<template>
  <div>
    <el-row :gutter="30">
      <el-col v-bind="grid">
        <div class="Nav">
          <div class="input" style="display: flex;">
            <el-input
              v-model="filterText"
              placeholder="选择分类"
              prefix-icon="el-icon-search"
              style="width:50%;"
              clearable
              class="mr15"
            />
            <el-button v-has="'site/attachcate/add'" title="添加分类" icon="el-icon-plus" size="small"  @click.stop="add"></el-button>
          </div>
          <div class="trees-coadd">
            <div class="scollhide">
              <div class="trees">
                <el-tree
                  ref="tree"
                  :data="treeData2"
                  :filter-node-method="filterNode"
                  :props="defaultProps"
                  highlight-current
                >
                  <div slot-scope="{ node, data}" class="custom-tree-node" @click.stop="handleNodeClick(data)">
                    <div>
                      <span>{{ node.label }}</span>
                      <span
                        v-if="data.space_property_name"
                        style="font-size: 11px;color: #3889b1"
                      >（{{ data.cate_name }}）</span>
                    </div>
                    <span class="el-ic">



                      <i  v-if="data.cate_id "
                        class="el-icon-edit mr5"
                        title="修改"
                        @click.stop="edit(data.cate_id)"
                        v-has="'site/attachcate/edit'"
                      />

                      <i  v-if="data.cate_id"
                        class="el-icon-delete"
                        title="删除分类"
                        @click.stop="() => deleteCate(data.cate_id)"
                        v-has="'site/attachcate/del'"
                      />
                    </span>
                  </div>
                </el-tree>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col v-bind="grid2" class="colLeft">
        <div v-loading="loading" class="conter">
          <div class="bnt">
            <el-upload  class="upload-demo ml10 mr10 mb15"  :action="uploadurl" :on-success="handleSuccess" :before-upload="beforeUpload" :headers="myHeaders"   :show-file-list="false" multiple>
                <el-button v-has="'general/upload'" size="mini" type="success">点击上传</el-button>
            </el-upload>
            <el-button
              v-if="params !== '/set/site/attachment'"
              size="mini"
              type="primary"
              class="mb10 mr10"
              @click="selectPics"
            >使用选中图片
            </el-button>
            <el-button v-has="'site/attachment/del'" type="danger" size="mini" class="mr10"  :disabled="checkPicList.length===0"   @click.stop="delPicList('图片')">删除图片
            </el-button>
            <el-select v-has="'site/attachment/change'"  v-model="sleOptions.cate_name" placeholder="图片移动至" class="mb15 ml10" size="mini">
              <el-option :label="sleOptions.cate_name" :value="sleOptions.cate_id"   style="max-width: 560px;height:200px;overflow: auto;background-color:#fff">
                <el-tree ref="tree2" :data="treeData2" :filter-node-method="filterNode" :props="defaultProps" highlight-current @node-click="handleSelClick"/>
              </el-option>
            </el-select>
          </div>
          <div class="pictrueList acea-row mb15">
            <div v-show="isShowPic" class="imagesNo">
              <i class="el-icon-picture" style="font-size: 60px;color: rgb(219, 219, 219);" />
              <span class="imagesNo_sp">图片库为空</span>
            </div>
            <div class="conters">
              <div
                v-for="(item, index) in pictrueList.list"
                :key="index"
                class="gridPic"
              >
                <img
                  v-lazy="item.url"
                  :class="item.isSelect ? 'on': '' "
                  @click="changImage(item, index, pictrueList.list)"
                >
              </div>
            </div>
          </div>
          <div class="pagination">
            <el-pagination
              :page-sizes="[12, 20, 40]"
              :page-size="tableData.pagesize"
              :current-page="tableData.page"
              layout="total, sizes, prev, pager, next"
              :total="pictrueList.total"
              @size-change="handleSizeChange"
              @current-change="pageChange"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth'

  import {
    cate_index,
    cate_add,
    cate_edit,
    cate_del,
    attachment_index,
    attachment_del,
    attachment_change,
  } from '@/api/attach'

export default {
  name: 'Upload',
  props: {
    isMore: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      uploadurl:process.env.VUE_APP_BASE_API+'General/upload',
      loading: false,
      params: '',
      sleOptions: {
        cate_name: '',
        cate_id: ''
      },
      list: [],
      grid: {
        xl: 8,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 24
      },
      grid2: {
        xl: 16,
        lg: 16,
        md: 16,
        sm: 16,
        xs: 24
      },
      filterText: '',
      treeData: [],
      treeData2: [],
      defaultProps: {
        children: 'children',
        label: 'cate_name'
      },
      classifyId: 0,
      myHeaders: { 'token': getToken() },
      tableData: {
        page: 1,
        pagesize: 12,
        s_cate_id: 0,
      },
      pictrueList: {
        list: [],
        total: 0
      },
      isShowPic: false,
      checkPicList: [],
      ids: [],
      checkedMore: [],
      checkedAll: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.params = this.$route && this.$route.path ? this.$route.path : ''
    if (this.$route && this.$route.query.field === 'dialog') import('../../../public/UEditor/dialogs/internal')
    this.getList()
    this.getFileList()
  },
  methods: {
    // 搜索分类
    filterNode(value, data) {
      if (!value) return true
      return data.cate_name.indexOf(value) !== -1
    },
    // 所有分类
    getList() {
      const data = {
        cate_name: '全部图片',
        cate_id: 0
      }
      cate_index().then(res => {
        this.treeData = res.data
        this.treeData.unshift(data)
        this.treeData2 = [...this.treeData]
      })
    },
    add(){
      this.$modalForm(cate_add()).then(() => this.getList())
    },
    edit(id) {
      this.$modalForm(cate_edit({id:id})).then(() => this.getList())
    },
    deleteCate(id) {
      let _this=this;
      _this.$modalSure().then(() => {
        cate_del({ids:id}).then(res => {
          _this.$message.success(res.msg)
          _this.getList()
        })
      })
    },

    handleNodeClick(data) {
      this.tableData.s_cate_id = data.cate_id
      this.getFileList()
    },
    // 上传成功
    handleSuccess(res) {
      if(res.code==1){

        this.$message({
          message:'上传成功',
          type: 'success',
          duration: 500,
        })

        this.tableData.s_cate_id = 0
        this.getFileList()
      }else{
        this.$message.error(res.msg);
      }
    },

    //上传之前
    beforeUpload(file) {
        let types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        const isImage = types.includes(file.type);
        if (!isImage) {
           this.$message.error('上传图片格式不正确!');
        }
        const isLtSize = file.size / 1024 / 1024 < 5;
        if (!isLtSize) {
           this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isImage && isLtSize;
    },

    // 文件列表
    getFileList() {
      this.loading = true
      attachment_index(this.tableData).then(async res => {
        this.pictrueList.list = res.data.list
        if (this.pictrueList.list.length) {
          this.isShowPic = false
        } else {
          this.isShowPic = true
        }
        if (this.$route && this.$route.query.field && this.$route.query.field !== 'dialog') this.checkedMore = window.form_create_helper.get(this.$route.query.field) || []
        this.pictrueList.total = res.data.total
        this.loading = false
      })
    },
    pageChange(page) {
      this.tableData.page = page
      this.getFileList()
    },
    handleSizeChange(val) {
      this.tableData.pagesize = val
      this.getFileList()
    },
    // 选中图片
    changImage(item, index, row) {
      let selectItem = ''
      this.$set(item, 'isSelect', item.isSelect === undefined ? true : !item.isSelect)
      selectItem = this.pictrueList.list.filter((item) => {
        return item.isSelect === true
      })
      this.ids = []
      const pic = []
      selectItem.map((item, index) => {
        this.ids.push(item.id)
        pic.push(item.url)
      })
      this.checkPicList = pic


    },
    // 点击使用选中图片
    selectPics() {
      if (this.checkPicList.length) {
        if (this.$route) {
          if (this.$route.query.type === '1') {
            if (this.checkPicList.length > 1) return this.$message.warning('最多只能选一张图片')
            /* eslint-disable */
              form_create_helper.set(this.$route.query.field, this.checkPicList[0])
              form_create_helper.close(this.$route.query.field)
            }
            if (this.$route.query.type === '2') {
              this.checkedAll = [...this.checkedMore, ...this.checkPicList]
              form_create_helper.set(this.$route.query.field, this.checkedAll)
              form_create_helper.close(this.$route.query.field)
            }
            if (this.$route.query.field === 'dialog') {
              let str = ''
              for (let i = 0; i < this.checkPicList.length; i++) {
                str += '<img src="' + this.checkPicList[i] + '">'
              }
              /* eslint-disable */
              nowEditor.editor.execCommand('insertHtml', str)
              nowEditor.dialog.close(true)
            }
          } else {
            if (this.isMore === '1' && this.checkPicList.length > 1) {
              return this.$message.warning('最多只能选一张图片')
            }
            this.$emit('getImage', this.checkPicList)
          }
        } else {
          this.$message.warning('请先选择图片')
        }
      },
      // 删除图片
      delPicList(tit) {
        const ids = {
          ids: this.ids
        }
        let _this=this;
        _this.$modalSure().then(() => {
          attachment_del(ids).then(res => {
            _this.$message.success(res.msg)
            _this.getFileList()
          })
        })

      },
      // 移动分类点击
      handleSelClick(node) {
        if (this.ids.length) {
          this.sleOptions = {
            cate_name: node.cate_name,
            cate_id: node.cate_id
          }


          attachment_change({ids:this.ids,cate_id:this.sleOptions.cate_id}).then(res => {
            this.$message.success(res.msg)
            this.clearBoth()
            this.getFileList()
          })


        } else {
          this.$message.warning('请先选择图片')
        }
      },

      clearBoth() {
        this.sleOptions = {
          cate_name: '',
          cate_id: ''
        }
        this.checkPicList = []
        this.ids = []
      }

    }
  }
</script>

<style scoped lang="scss">
  .selectTreeClass {
    background: #d5e8fc;
  }

  .treeBox {
    width: 100%;
    height: 100%;
  }

  .upload-demo {
    display: inline-block !important;
  }

  .tree_w {
    padding: 20px 30px
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    color: #4386c6;

    div {
      span {
        width: 100px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

  }

  .custom-tree-node > div > span {
    display: inline-block;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-ic {
    display: none;

    i, span {
      /*padding: 0 14px;*/
      font-size: 18px;
      font-weight: 600;
    }

    .svg-icon {
      color: #4386c6;
    }
  }

  .el-tree-node__content {
    height: 38px;
  }

  .el-tree-node__expand-icon {
    color: #428bca;
    /*padding: 10px 10px 0px 10px !important;*/
  }

  .el-tree-node__content:hover .el-ic {
    color: #428bca !important;
    display: inline-block;
  }

  .el-tree-node__content:hover {
    font-weight: bold;
  }

  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content :hover {
    .el-tree-node__expand-icon.is-leaf {
      color: transparent;
      cursor: default;
    }

    /*background-color: #3998d9;*/
    .custom-tree-node {
      font-weight: bold;
    }

    .el-tree-node__expand-icon {
      font-weight: bold;
    }
  }

  .el-dialog__body {
    .upload-container .image-preview .image-preview-wrapper img {
      height: 100px;
    }

    .el-dialog .el-collapse-item__wrap {
      padding-top: 0px;

    }

    .spatial_img {
      .el-collapse-item__wrap {
        margin-bottom: 0;
        padding-top: 0px;
      }
    }

    .upload-container .image-preview .image-preview-wrapper {
      width: 120px;
    }

    .upload-container .image-preview .image-preview-action {
      line-height: 100px;
      height: 100px;
    }
  }

  .trees-coadd {
    min-width: 100%;
    border-radius: 4px;
    overflow-x: auto;
    position: relative;

    .scollhide {
      overflow-x: hidden;
      overflow-y: scroll;
      padding: 10px 0 10px 0;
      box-sizing: border-box;

      .trees {
        width: 100%;
        max-height: 374px;
      }
    }

    .scollhide::-webkit-scrollbar {
      display: none;
    }
  }

  .conters {
    display: flex;
    flex-wrap: wrap;
  }

  .gridPic {
    margin-right: 20px;
    margin-bottom: 10px;
    width: 110px;
    height: 110px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }

  .conter {
    width: 99%;
    height: 100%;

    .bnt {
      width: 100%;
      padding: 0 13px 10px 15px;
      box-sizing: border-box;
    }

    .pictrueList {
      padding-left: 15px;
      width: 100%;

      el-image {
        width: 100%;
        border: 2px solid #fff;
      }

      .on {
        border: 2px solid #5FB878;
      }
    }

    .imagesNo {
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      margin: 65px auto;

      .imagesNo_sp {
        font-size: 13px;
        color: #dbdbdb;
        line-height: 3;
      }
    }
  }
</style>
